package com.cheyunkeji.er.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;

import com.cheyunkeji.er.view.SToast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Michael on 2017/4/27 14:10.
 */

/**
 * 图片压缩处理工具类
 */
public class PictureCompressUtil {

    private static final String TAG = PictureCompressUtil.class.getSimpleName();

    public static String compressImage(String filePath, String targetPath, int quality) {

        Bitmap bm = getSmallBitmap(filePath);//获取一定尺寸的图片
        int degree = readPictureDegree(filePath);//获取相片拍摄角度
        if (degree != 0) {//旋转照片角度，防止头像横着显示
            bm = rotateBitmap(bm, degree);
        }
        File outputFile = new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
            } else {
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);

        } catch (Exception e) {
        }
        return outputFile.getPath();
    }


    /**
     * 返回压缩后的图片的Base64位编码String
     *
     * @param imgPath
     * @return
     */
    public static String compressImageReturnAsBase64String(String imgPath, Context context) {

        Uri uri;

//        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
//            uri = Uri.fromFile(new File(imgPath));
//
//        } else {
//            uri = FileProvider.getUriForFile(context, ProviderUtil.getFileProviderName(context), new File(imgPath));
//
//            Log.e(TAG, "compressImageReturnAsBase64String: " + uri.toString());
//        }

        Bitmap bm = BitmapFactory.decodeFile(imgPath);
//      Bitmap bm = getSmallBitmapByUri(context,uri);//获取一定尺寸的图片

//        return getCompressBitmap(context,uri);

//        return CompressBitmap(getSmallBitmap(imgPath));

//        return CompressBitmap(getSmallBitmapByUri(context, uri));


//        int degree = readPictureDegree(imgPath);//获取相片拍摄角度
//        if (degree != 0) {//旋转照片角度，防止头像横着显示
//            bm = rotateBitmap(bm, degree);
//        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);

        byte[] bytes = baos.toByteArray();
//        bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = new String(encode);

        return encodeString;

    }


    /**
     * 压缩图片，并以字节数组形式返回，用于Aliyun图片上传前的压缩处理
     *
     * @param imgPath
     * @param quality
     * @return
     */
    public static byte[] compressImageReturnAsByteArray(String imgPath, int quality) {

        Bitmap bm = getSmallBitmap(imgPath);//获取一定尺寸的图片


//        int degree = readPictureDegree(imgPath);//获取相片拍摄角度
//        if (degree != 0) {//旋转照片角度，防止头像横着显示
//            bm = rotateBitmap(bm, degree);
//        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);

        return baos.toByteArray();

    }


    /**
     * 根据路径获得图片信息并按比例压缩，返回bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);

    }


    public static Bitmap getSmallBitmapByUri(Context context, Uri uri) {

        try {
            return MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 返回图片Base64编码
     *
     * @param context
     * @param imageUri
     * @return
     */
    public static String getCompressBitmap(Context context, Uri imageUri) {

        InputStream inputStream = null;

        try {

            inputStream = context.getContentResolver().openInputStream(imageUri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            BitmapFactory.decodeStream(inputStream, null, options);
            int originalWidth = options.outWidth;
            int originalHeight = options.outHeight;
            if (originalHeight == -1 || originalWidth == -1) return null;
            float height = 1280f;
            float width = 960f;
            int noCompress = 1;
            if (originalWidth > originalHeight && originalWidth > width) {
                noCompress = (int) (originalWidth / width);
            } else if (originalWidth < originalHeight && originalHeight > height) {
                noCompress = (int) (originalHeight / height);
            }
            if (noCompress <= 0) noCompress = 1;
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmapOptions.inSampleSize = noCompress;
            options.inJustDecodeBounds = true;
            bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
            inputStream = context.getContentResolver().openInputStream(imageUri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, bitmapOptions);
            inputStream.close();
            return CompressBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    private static String CompressBitmap(Bitmap mBitmap) {

        if (null == mBitmap) {

            SToast.show("Bitmap is Empty");
            return null;

        }

        Bitmap bitmap = Bitmap.createBitmap(mBitmap,0,0,191,129,null,false);

        int options = 100;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);  //先不压缩，数据保存到outputStream；
//        LogUtils.e("yasuo", outputStream.toByteArray().length / 1024 + "11================");
        while (outputStream.toByteArray().length / 1024 > 350) {//循环判断如果压缩后图片是否大于400kb,大于继续压缩
            outputStream.reset(); //重置
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, outputStream);
//            LogUtils.e("yasuo", outputStream.toByteArray().length / 1024 + "================" + options);
            options -= 10;//每次都减少10
        }

//        outputStream.toByteArray();
//        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
//        Bitmap decodeStream = BitmapFactory.decodeStream(inputStream, null, null);

        byte[] bytes = outputStream.toByteArray();

        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = new String(encode);

        return encodeString;
    }


    /**
     * 获取照片角度
     *
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转照片
     *
     * @param bitmap
     * @param degress
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}
